package com.thread.collection.Map;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

public class ConcurrentHashMapTest {


    static Map<UUID,UUID> m = new ConcurrentHashMap<>();

    static int count = Constants.COUNT;
    static UUID[] keys = new UUID[count];
    static UUID[] values = new UUID[count];

    static final int THREAD_COUNT = Constants.THREAD_COUNT;
    static{
        for(int i=0;i<count;i++){
            keys[i] = UUID.randomUUID();
            values[i] = UUID.randomUUID();
        }
    }
    static class MyThread extends Thread{
        int start;
        int grap = count / THREAD_COUNT;
        public MyThread(int start){
            this.start = start;
        }

        @Override
        public void run() {
            for(int i=start;i<start+grap;++i){
                m.put(keys[i],values[i]);
            }
        }
    }

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        Thread[] ts = new Thread[THREAD_COUNT];

        for(int i=0;i<THREAD_COUNT;i++){
            ts[i] = new HashTableTest.MyThread(i*(count / THREAD_COUNT));
        }

        for(int i=0;i<ts.length;++i){
            ts[i].start();;
        }

        for(int i=0;i<ts.length;++i){
            try {
                ts[i].join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println(System.currentTimeMillis() - start);

        System.out.println("---------------------------");

        start = System.currentTimeMillis();
        for(int i=0;i<THREAD_COUNT;i++){
            ts[i] = new Thread(()->{
                int capcity = (count / THREAD_COUNT);
                for(int j=0;j<capcity;++j){
                    m.get(keys[10]);
                }
            });
        }

        for(int i=0;i<ts.length;++i){
            ts[i].start();;
        }

        for(int i=0;i<ts.length;++i){
            try {
                ts[i].join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println(System.currentTimeMillis() - start);
    }

}
